import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

export interface PDFOptions {
  filename?: string;
  orientation?: 'portrait' | 'landscape';
  format?: 'a4' | 'a3' | 'letter';
  quality?: number;
}

export const generatePDF = async (
  elementId: string, 
  options: PDFOptions = {}
): Promise<void> => {
  const {
    filename = '族谱.pdf',
    orientation = 'portrait',
    format = 'a4',
    quality = 1
  } = options;

  try {
    const element = document.getElementById(elementId);
    if (!element) {
      throw new Error(`Element with id "${elementId}" not found`);
    }

    // 创建canvas
    const canvas = await html2canvas(element, {
      scale: quality,
      useCORS: true,
      allowTaint: true,
      backgroundColor: '#ffffff',
      logging: false,
      width: element.scrollWidth,
      height: element.scrollHeight,
      scrollX: 0,
      scrollY: 0
    });

    const imgData = canvas.toDataURL('image/png');
    
    // 创建PDF
    const pdf = new jsPDF({
      orientation,
      unit: 'mm',
      format
    });

    // 获取PDF页面尺寸
    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight = pdf.internal.pageSize.getHeight();
    
    // 计算图片尺寸
    const imgWidth = canvas.width;
    const imgHeight = canvas.height;
    const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
    
    const scaledWidth = imgWidth * ratio;
    const scaledHeight = imgHeight * ratio;
    
    // 居中显示
    const x = (pdfWidth - scaledWidth) / 2;
    const y = (pdfHeight - scaledHeight) / 2;

    // 如果内容高度超过一页，需要分页
    if (scaledHeight > pdfHeight) {
      let position = 0;
      const pageHeight = pdfHeight;
      
      while (position < scaledHeight) {
        if (position > 0) {
          pdf.addPage();
        }
        
        pdf.addImage(
          imgData,
          'PNG',
          x,
          -position,
          scaledWidth,
          scaledHeight
        );
        
        position += pageHeight;
      }
    } else {
      pdf.addImage(imgData, 'PNG', x, y, scaledWidth, scaledHeight);
    }

    // 下载PDF
    pdf.save(filename);
  } catch (error) {
    console.error('PDF生成失败:', error);
    throw error;
  }
};

export const generateTablePDF = async (
  elementId: string,
  options: PDFOptions = {}
): Promise<void> => {
  const {
    filename = '族谱表格.pdf',
    orientation = 'landscape',
    format = 'a3',
    quality = 2
  } = options;

  try {
    const element = document.getElementById(elementId);
    if (!element) {
      throw new Error(`Element with id "${elementId}" not found`);
    }

    // 找到表格元素
    const table = element.querySelector('table');
    if (!table) {
      throw new Error('Table not found in the specified element');
    }

    // 临时移除父容器的滚动限制
    const parentContainer = element.parentElement;
    const originalStyles = {
      overflow: element.style.overflow,
      height: element.style.height,
      maxHeight: element.style.maxHeight,
      parentOverflow: parentContainer?.style.overflow,
      parentHeight: parentContainer?.style.height,
      parentMaxHeight: parentContainer?.style.maxHeight
    };

    // 设置为无滚动，自动高度
    element.style.overflow = 'visible';
    element.style.height = 'auto';
    element.style.maxHeight = 'none';
    
    if (parentContainer) {
      parentContainer.style.overflow = 'visible';
      parentContainer.style.height = 'auto';
      parentContainer.style.maxHeight = 'none';
    }

    // 等待DOM更新
    await new Promise(resolve => setTimeout(resolve, 100));

    // 创建canvas，确保捕获完整内容
    const canvas = await html2canvas(table, {
      scale: quality,
      useCORS: true,
      allowTaint: true,
      backgroundColor: '#ffffff',
      logging: false,
      width: table.scrollWidth,
      height: table.scrollHeight,
      scrollX: 0,
      scrollY: 0
    });

    // 恢复原始样式
    element.style.overflow = originalStyles.overflow;
    element.style.height = originalStyles.height;
    element.style.maxHeight = originalStyles.maxHeight;
    
    if (parentContainer) {
      parentContainer.style.overflow = originalStyles.parentOverflow || '';
      parentContainer.style.height = originalStyles.parentHeight;
      parentContainer.style.maxHeight = originalStyles.parentMaxHeight;
    }

    const imgData = canvas.toDataURL('image/png');
    
    // 创建PDF
    const pdf = new jsPDF({
      orientation,
      unit: 'mm',
      format
    });

    // 获取PDF页面尺寸
    const pdfWidth = pdf.internal.pageSize.getWidth();
    const pdfHeight = pdf.internal.pageSize.getHeight();
    
    // 计算图片尺寸
    const imgWidth = canvas.width;
    const imgHeight = canvas.height;
    const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
    
    const scaledWidth = imgWidth * ratio;
    const scaledHeight = imgHeight * ratio;
    
    // 居中显示
    const x = (pdfWidth - scaledWidth) / 2;
    const y = (pdfHeight - scaledHeight) / 2;

    // 如果内容高度超过一页，需要分页
    if (scaledHeight > pdfHeight) {
      let position = 0;
      const pageHeight = pdfHeight;
      
      while (position < scaledHeight) {
        if (position > 0) {
          pdf.addPage();
        }
        
        pdf.addImage(
          imgData,
          'PNG',
          x,
          -position,
          scaledWidth,
          scaledHeight
        );
        
        position += pageHeight;
      }
    } else {
      pdf.addImage(imgData, 'PNG', x, y, scaledWidth, scaledHeight);
    }

    // 下载PDF
    pdf.save(filename);
  } catch (error) {
    console.error('PDF生成失败:', error);
    throw error;
  }
};